#include "Mail.h"
#include "ui_Mail.h"
#include "Mainpage.h"
#include <QMessageBox>
#include <QHostAddress>
#include <QBitmap>
#include <QStyleOption>
#include "mymessagebox.h"

Mail::Mail(const QString &id, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Mail)
    , employeeId(id)  // 通过构造函数传递工号
    , tcpSocket(new QTcpSocket(this))
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 初始化 QTableView 的数据模型
    resignatureModel = new QStandardItemModel(this);
    resignatureModel->setHorizontalHeaderLabels({"申请时间", "申请状态"});
    ui->resignature->setModel(resignatureModel);

    vacationModel = new QStandardItemModel(this);
    vacationModel->setHorizontalHeaderLabels({"申请时间", "申请状态"});
    ui->vacation->setModel(vacationModel);

    faceModel = new QStandardItemModel(this);
    faceModel->setHorizontalHeaderLabels({"申请时间", "申请状态"});
    ui->face->setModel(faceModel);

    // 连接到服务器
    tcpSocket->connectToHost(QHostAddress("127.0.0.1"), 12351);
    if (!tcpSocket->waitForConnected(3000)) {
        // QMessageBox::warning(this, "错误", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 发送 employeeId 请求数据
    QString request = "FETCH_DATA:" + employeeId;
    tcpSocket->write(request.toUtf8());
    tcpSocket->flush();

    // 处理服务器返回的数据
    connect(tcpSocket, &QTcpSocket::readyRead, this, [=]() {
        QByteArray response = tcpSocket->readAll();
        QStringList dataList = QString(response).split(";");

        // 清空模型中的现有数据
        resignatureModel->removeRows(0, resignatureModel->rowCount());
        vacationModel->removeRows(0, vacationModel->rowCount());
        faceModel->removeRows(0, faceModel->rowCount());

        // 解析并填充 ReSignTable 的数据
        int index = 0;
        while (index < dataList.size() && dataList[index] != "LEAVE_START") {
            QStringList entry = dataList[index].split(",");
            QList<QStandardItem*> row;
            if (entry.size() == 2) {  // 确保entry有两个元素
                row << new QStandardItem(entry[0])
                    << new QStandardItem(getStatusString(entry[1].toInt()));
                resignatureModel->appendRow(row);
            }
            index++;
        }

        // 解析并填充 LeaveTable 的数据
        index++;
        while (index < dataList.size() && dataList[index] != "FACE_START") {
            QStringList entry = dataList[index].split(",");
            if (entry.size() == 2) {
                QList<QStandardItem*> row;
                row << new QStandardItem(entry[0])
                    << new QStandardItem(getStatusString(entry[1].toInt()));
                vacationModel->appendRow(row);
            }
            index++;
        }

        // 解析并填充 FaceVerification 的数据
        index++;
        while (index < dataList.size()) {
            QStringList entry = dataList[index].split(",");
            if (entry.size() == 2) {
                QList<QStandardItem*> row;
                row << new QStandardItem(entry[0])
                    << new QStandardItem(getStatusString(entry[1].toInt()));
                faceModel->appendRow(row);
            }
            index++;
        }
    });
}

Mail::~Mail()
{
    delete ui;
}

// 实现窗口拖动功能
void Mail::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 50) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Mail::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Mail::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 20, 20); // 在 bitmap 中绘制圆角矩形

    // 手动绘制边框
    QPainter borderPainter(this);
    borderPainter.setRenderHint(QPainter::Antialiasing);
    QPen pen(QColor("#55aaff")); // 设置边框颜色
    pen.setWidth(2);              // 设置边框宽度
    borderPainter.setPen(pen);
    borderPainter.setBrush(Qt::NoBrush);
    QRect rect = this->rect();
    rect.adjust(1, 1, -1, -1); // 调整边框矩形，以确保边框在控件内部
    borderPainter.drawRoundedRect(rect, 20, 20); // 绘制圆角边框

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Mail::on_returnButton_clicked()
{
    this->close();
}

QString Mail::getStatusString(int status)
{
    switch (status) {
    case 0:
        return "审核中";
    case 1:
        return "审核通过";
    case 2:
        return "审核未通过";
    default:
        return "未知状态";
    }
}
